<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.name"
          placeholder="请输入任务名称"
          clearable
          size="small"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
        <el-select v-model="query.status" style="width: 200px;" placeholder="请选择发布状态" class="filter-item" clearable>
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <crudOperation show="" :permission="permission" />

    </div>
    <el-table
      ref="table"
      v-loading="crud.loading"
      style="width: 100%;"
      :data="crud.data"
      @filter-change="crud.handleFilterChange"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('taskName')" prop="taskName" label="任务名称" />
      <el-table-column v-if="columns.visible('status')" prop="status" label="发布状态">
        <template slot-scope="scope">
          {{ findStatusName(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('taskType')" prop="taskType" label="发布任务类型" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="2" />
    <!-- 新增页面 -->
    <el-dialog
      v-if="crud.status.cu > 0 || detailsFlag === true"
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeDialog"
      :visible.sync="crud.status.cu > 0 || detailsFlag === true"
      :title="crud.status.title"
      width="1200px"
      top="5vh"
    >
      <el-form ref="form" v-loading="isloading" :model="form" :rules="rules" :inline="true" label-width="250px">
        <el-row>
          <el-col :span="24">
            <el-steps :active="active" finish-status="success" simple>
              <el-step title="基本信息" />
              <el-step title="节点" />
              <el-step title="冒烟" />
              <!-- <el-step title="部署" /> -->
            </el-steps>
          </el-col>
        </el-row>
        <el-row>
          <div v-if="active===0">
            <basic-info ref="basicInfo" v-model="form" />
            <div class="dialog-footer" style="text-align: center;margin-top: 10px;">
              <el-button @click="closeDialog">关 闭</el-button>
              <el-button type="primary" @click="next">下一步</el-button>
            </div>
          </div>
          <div v-if="active===1">
            <create-file v-model="form" />
            <div class="dialog-footer" style="text-align: center;margin-top: 40px;">
              <el-button @click="prev">上一步</el-button>
              <el-button type="primary" @click="next">下一步</el-button>
            </div>
          </div>
          <div v-if="active===2">
            <run-smoke-test v-model="form" />
            <div class="dialog-footer" style="text-align: center;margin-top: 40px;">
              <el-button @click="prev">上一步</el-button>
              <el-button type="primary" :disabled="form.publishStauts >= 3" @click="next">冒 烟</el-button>
            </div>
          </div>
          <!-- <div v-if="active===3">
            <deploy-file v-model="form" />
            <div class="dialog-footer" style="text-align: center;margin-top: 40px;">
              <el-button @click="prev">上一步</el-button>
              <el-button type="primary" :disabled="form.publishStauts > 3" @click="next">部 署</el-button>
            </div>
          </div> -->
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/expand/golive/publish/CRUD.operation'
import pagination from '@crud/Pagination'
import publishTaskApi from '@/api/golive/alibabaPublish/publishTask'
import publishTaskProcessApi from '@/api/golive/alibabaPublish/publishTaskProcess'
import publishTaskProcessFileApi from '@/api/golive/alibabaPublish/publishTaskProcessFile'
import publishTaskScriptApi from '@/api/golive/alibabaPublish/publishTaskScript'
import publishTaskScriptParamApi from '@/api/golive/alibabaPublish/publishTaskScriptParam'
import basicInfo from './../components/process/basicInfo'
import createFile from './../components/process/createFile'
import runSmokeTest from './../components/process/runSmokeTest'

const defaultCrud = CRUD({
  title: '发布',
  url: '/api/deploy/task',
  crudMethod: { ...publishTaskApi }
})
const defaultForm = {
  pkId: null,
  taskName: '',
  scriptSelectType: 'onlineDb',
  sourceCode: null,
  dbName: null,
  businessPkId: null,
  status: 'TODO',
  publishScriptList: [],
  processFileID: [],
  runSmokeTestConf: '{\n    "ProjectEnv": "PROD",\n    "Bizdate": "2020-05-26 00:00:00"\n}',
  publishStauts: 0
}
export default {
  components: { crudOperation, rrOperation, pagination, basicInfo, createFile, runSmokeTest },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      enabledTypeOptions: [
        { key: 'TODO', display_name: '待发布', step: 1 },
        { key: 'CREATEFILE', display_name: '提交文件', step: 2 },
        { key: 'SUBMITFILE', display_name: '提交文件', step: 2 },
        { key: 'RUNSMOKETEST', display_name: '冒烟', step: 3 },
        { key: 'FINISH', display_name: '已发布', step: 3 }
      ],
      detailsFlag: false,
      isloading: false,
      active: 1,
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        businessPkId: [
          { required: true, message: '请选择业务流程', trigger: 'blur' }
        ]
      },
      permission: {
        add: ['admin', 'aliPublish:add'],
        edit: ['aliPublish:edit'],
        del: ['aliPublish:del']
      },
      textarea: ''
    }
  },
  methods: {
    findStatusName(val) {
      const opt = this.enabledTypeOptions.find(opt => opt.key === val.toUpperCase())
      if (opt !== undefined) {
        return opt.display_name
      }
    },
    findStatusStep(val) {
      const opt = this.enabledTypeOptions.find(opt => opt.key === val.toUpperCase())
      if (opt !== undefined) {
        return opt.step
      } else {
        return 0
      }
    },
    initForm() {
      this.form.pkId = null
      this.form.taskName = ''
      this.form.scriptSelectType = 'onlineDb'
      this.form.sourceCode = null
      this.form.dbName = null
      this.form.businessPkId = null
      this.form.status = 'TODO'
      this.form.publishScriptList = []
      this.form.runSmokeTestConf = '{\n    "ProjectEnv": "PROD",\n    "Bizdate": "2020-05-25 00:00:00"\n}'
      this.form.publishStauts = 0
    },
    // 新增
    [CRUD.HOOK.beforeToCU](crud) {
      this.initForm()
      this.active = 0
    },
    async next() {
      let check = true
      this.isloading = true
      if (this.active === 0 && this.active >= this.form.publishStauts) {
        this.$refs.basicInfo.resetQuery()
        await this.$refs['form'].validate((valid) => {
          if (!(valid && this.checkSelectScript())) {
            check = false
            return
          }
        })
        if (!check) {
          this.isloading = false
          return false
        }
        this.translateSubmitDate()
        await publishTaskApi.add(this.form).then(res => {
          this.form.pkId = res
          this.$notify({ title: '成功', message: '新增任务成功！', type: 'success' })
        }).catch(() => {
          this.$notify({ title: '告警', message: '新增任务失败！', type: 'warning' })
          check = false
        })

        if (!check) {
          this.isloading = false
          return false
        }

        // 获取当前任务脚本
        const param = {
          'deployTaskPkId': this.form.pkId,
          'page': 0,
          'size': 10000
        }
        this.form.publishScriptList = []
        publishTaskScriptApi.findListByPage(param).then(data => {
          data.content.forEach(script => {
            let inputArray = []
            if (this.form.publishStauts >= 2) {
              inputArray = script.inputList.split(',')
            }
            const publishScript = { pkId: script.pkId, taskPkId: script.deployTaskPkId, scriptConvertListPkId: null, scriptName: script.convertFileName, status: script.status, processFileID: inputArray }
            this.form.publishScriptList.push(publishScript)
          })
        })
      } else if (this.active === 1 && this.active >= this.form.publishStauts) {
        if (!this.checkSelectScriptFile()) {
          this.isloading = false
          return
        }
        const processForm = {}
        processForm.deployTaskPkId = this.form.pkId
        // processForm.processType = 'CreateFile'
        processForm.scriptListVoList = []
        this.form.publishScriptList.forEach(item => {
          const inputData = item.processFileID.join(',')
          const data = { pkId: item.pkId, inputList: inputData, inputFileNameList: inputData }
          processForm.scriptListVoList.push(data)
        })
        await publishTaskProcessFileApi.createFile(processForm).then(res => {
          this.form.status = 'CREATEFILE'
          this.$notify({ title: '成功', message: '新增节点成功！', type: 'success' })
        }).catch(() => {
          this.$notify({ title: '告警', message: '新增节点失败！', type: 'warning' })
          check = false
        })
        if (!check) {
          this.isloading = false
          return false
        }
      } else if (this.active === 2 && this.active >= this.form.publishStauts) {
        const processForm = {}
        processForm.deployTaskPkId = this.form.pkId
        processForm.processType = 'RunSmokeTest'
        processForm.deployParam = this.form.runSmokeTestConf
        await publishTaskProcessApi.create(processForm).then(res => {
          this.closeDialog()
          this.form.status = 'FINISH'
          this.$notify({ title: '成功', message: '冒烟测试成功！', type: 'success' })
        }).catch(() => {
          this.$notify({ title: '告警', message: '冒烟测试失败！', type: 'warning' })
          check = false
        })
        if (!check) {
          this.isloading = false
          return false
        }
      } else if (this.active === 2) {
        this.closeDialog()
      }
      // else if (this.active === 3 && this.active >= this.form.publishStauts) {
      //   const processForm = {}
      //   processForm.deployTaskPkId = this.form.pkId
      //   processForm.processType = 'DeployFile'
      //   await publishTaskProcessApi.create(processForm).then(res => {
      //     this.form.status = 'FINISH'
      //     this.closeDialog()
      //     this.$notify({ title: '成功', message: '部署成功！', type: 'success' })
      //   }).catch(() => {
      //     this.$notify({ title: '告警', message: '部署失败！', type: 'warning' })
      //     check = false
      //   })
      //   if (!check) {
      //     return false
      //   }
      // }
      this.isloading = false
      this.form.publishStauts = this.findStatusStep(this.form.status)
      this.active++
    },
    // 创建任务前数据对象
    translateSubmitDate() {
      this.form.scriptIds = this.form.publishScriptList.map(id => id.scriptConvertListPkId).join(',')
    },
    closeDialog() {
      this.crud.cancelCU()
      this.detailsFlag = false
      this.active = 0
      this.form.publishStauts = 0
      this.crud.toQuery()
    },
    checkSelectScript() {
      if (this.form.publishScriptList.length < 1) {
        this.$notify({ title: '告警', message: '请选择要发布的脚本！', type: 'warning' })
        return false
      }
      return true
    },
    checkSelectScriptFile() {
      for (const script of this.form.publishScriptList) {
        if (script.processFileID === undefined || script.processFileID.length < 1) {
          this.$notify({ title: '告警', message: '请选择要依赖的节点！', type: 'warning' })
          return false
        }
      }
      return true
    },
    prev() {
      if (this.active > 0) {
        this.active--
      } else {
        this.active = 0
      }
    },
    // 查看详情
    toDetail(row) {
      this.form = Object.assign(this.form, row)
      this.form.scriptSelectType = 'onlineDb'
      this.form.publishStauts = this.findStatusStep(row.status)
      this.active = this.findStatusStep(row.status) < 3 ? this.findStatusStep(row.status) : 2
      // 获取当前任务脚本
      const param = {
        'deployTaskPkId': row.pkId,
        'page': 0,
        'size': 10000
      }
      publishTaskScriptApi.findListByPage(param).then(data => {
        data.content.forEach(script => {
          let inputArray = []
          if (this.form.publishStauts >= 2) {
            inputArray = script.inputList.split(',')
          }
          const publishScript = { pkId: script.pkId, taskPkId: script.deployTaskPkId, scriptConvertListPkId: null, scriptName: script.convertFileName, status: script.status, processFileID: inputArray }
          this.form.publishScriptList.push(publishScript)
        })
        if (this.form.publishStauts >= 3) {
          // 获取冒烟配置
          const param = {
            'deployTaskPkId': row.pkId,
            'processType': 'RunSmokeTest'
          }
          publishTaskScriptParamApi.findProcessParam(param).then(data => {
            const jsonDeployParam = {}
            jsonDeployParam.ProjectEnv = data.ProjectEnv
            jsonDeployParam.Bizdate = data.Bizdate
            this.form.runSmokeTestConf = JSON.stringify(JSON.parse(jsonDeployParam), null, '\n')
          })
        }
        this.detailsFlag = true
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-transfer-panel {
  width: 250px;
}

::v-deep .bordered-button {
  border: #92dab3 2px;
}

::v-deep .el-transfer__buttons button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .el-transfer__buttons button:first-child span span {
  margin-left: 0px;
}

.assist {
  min-height: 46px;
  color: #fff;
  background-color: #ff4949;
  border-color: #ff4949;
}
</style>
